package com.mall.b2c.service.impl;

import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.context.ApplicationContextException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import com.mall.b2c.bean.BrandBean;
import com.mall.b2c.dao.BrandDao;
import com.mall.b2c.domain.goods.BrandDomain;
import com.mall.b2c.domain.goods.GoodsDomain;
import com.mall.b2c.service.BrandService;
import com.mall.b2c.service.GoodsService;
import com.mall.common.bean.Order;
import com.mall.common.hibernate.Finder;
import com.mall.common.service.impl.BaseServiceImpl;


/**
 * Service实现类 - 品牌
 */
@Service("b2cBrandService")
@Transactional
public class BrandServiceImpl extends BaseServiceImpl<BrandDomain, Long> implements BrandService {
	@Resource private GoodsService goodsService;
	
	@Resource
	public void setBaseDao(BrandDao brandDao) { 
		super.setBaseDao(brandDao); 
	}

	@Override
	public List<BrandBean> getBrandList(Boolean isRecommend, Integer count, 
			String firstCharacter, String goodsCategoryCode, List<Order> orders) {
		String hql = null;
		if(StringUtils.isNotBlank(goodsCategoryCode)){
			hql = "select distinct new com.mall.b2c.bean.BrandBean(b) from BrandDomain b left join b.goodsSet g where g.goodsCategory is not null and g.goodsCategory.code like :goodsCategoryCode";
		}else{
			hql = "select new com.mall.b2c.bean.BrandBean(b) from BrandDomain b where 1 = 1";
		}
		Finder finder = Finder.create(hql);
		if(StringUtils.isNotBlank(goodsCategoryCode)){
			//TODO 通过一级分类查询所关联的品牌
			finder.setParam("goodsCategoryCode", StringUtils.substringBefore(goodsCategoryCode, ".")+"%");
		}
		if(isRecommend != null){
			finder.append(" and b.isRecommend = :isRecommend");
			finder.setParam("isRecommend", true);
		}
		if(StringUtils.isNotBlank(firstCharacter)){
			finder.append(" and b.firstCharacter like :firstCharacter");
			finder.setParam("firstCharacter", firstCharacter+"%");
		}
		if(count != null){
			finder.setMaxResults(count);
		}
		if(!CollectionUtils.isEmpty(orders)){
			for(Order order : orders){
				order.setFieldName("b."+order.getFieldName());
				finder.setOrder(order);
			}
		}
		return finder.findHQLList();
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void importBrandInfo(String type, MultipartFile multipartFile) throws Exception {
		InputStream input = multipartFile.getInputStream();
		HSSFWorkbook wb = new HSSFWorkbook(input);
		HSSFSheet sheet = wb.getSheetAt(0);
		Iterator<Row> it = sheet.rowIterator();
		if(it.hasNext()){
			it.next();
		}
		if("brand".equals(type)){
			importBrand(it);
		}else if("brandRelation".equals(type)){
			importBrandRelation(it);
		}
	}

	@Transactional(propagation=Propagation.REQUIRED)
	public void importBrand(Iterator<Row> it){
		String brandName, logo, advert, url, introduction;
		boolean isRecommend;
		Integer priority; 
		Cell cell = null;
		int index = 0;
		while(it.hasNext()){
			index++;
			Row row = it.next();
			cell = row.getCell(0);
			if(cell != null && StringUtils.isNotBlank(cell.getStringCellValue().trim())){
				brandName = cell.getStringCellValue().trim();
			}else{
				throw new ApplicationContextException("第" + index + "条记录的名称为空");
			}
			cell = row.getCell(1);
			if(cell != null && StringUtils.isNotBlank(cell.getStringCellValue().trim())){
				logo = cell.getStringCellValue().trim();
			}else{
				throw new ApplicationContextException("第" + index + "条记录的logo为空");
			}
			cell = row.getCell(2);
			if(cell != null){
				advert = cell.getStringCellValue();
			}else{
				advert = null;
			}
			cell = row.getCell(3);
			if(cell != null){
				url = cell.getStringCellValue();
			}else{
				url = null;
			}
			cell = row.getCell(4);
			if(cell != null){
				introduction = cell.getStringCellValue();
			}else{
				introduction = null;
			}
			cell = row.getCell(5);
			if(cell != null){
				isRecommend = "是".equals(cell.getStringCellValue());
			}else{
				isRecommend = false;
			}
			cell = row.getCell(6);
			if(cell != null && Pattern.matches("^\\d+$", cell.getStringCellValue())){
				priority = Integer.valueOf(cell.getStringCellValue());
			}else{
				priority = null;
			}
			
			BrandDomain brand = get("name", brandName);
			if(brand == null){
				brand = new BrandDomain();
				brand.setName(brandName);
				brand.setLogo(logo);
				brand.setAdvert(advert);
				brand.setUrl(url);
				brand.setIntroduction(introduction);
				brand.setIsRecommend(isRecommend);
				brand.setPriority(priority);
				persist(brand);
			}
		}
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	public void importBrandRelation(Iterator<Row> it){
		String goodsCode, brandName;
		Cell cell = null;
		while(it.hasNext()){
			Row row = it.next();
			cell = row.getCell(0);
			if(cell != null && StringUtils.isNotBlank(cell.getStringCellValue().trim())){
				goodsCode = cell.getStringCellValue().trim();
			}else{
				continue;
			}
			cell = row.getCell(1);
			if(cell != null && StringUtils.isNotBlank(cell.getStringCellValue().trim())){
				brandName = cell.getStringCellValue().trim();
			}else{
				continue;
			}
			BrandDomain brand = get("name", brandName);
			if(brand == null){
				continue;
			}
			GoodsDomain goods = goodsService.get("code", goodsCode);
			if(goods == null){
				continue;
			}
			goods.setBrand(brand);
			goodsService.update(goods);
		}
	}
}
